public class LinkedListCycleDetection {
    // 链表节点定义
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    // 判断链表是否有环的主方法
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true; // 相遇，有环
            }
        }
        return false; // 无环
    }

    public static void main(String[] args) {
        LinkedListCycleDetection solution = new LinkedListCycleDetection();

        // 创建无环链表 1->2->3->4
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        head1.next.next.next = new ListNode(4);
        System.out.println("无环链表检测结果: " + solution.hasCycle(head1));

        // 创建有环链表 1->2->3->4->2（环的入口为2）
        ListNode head2 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        head2.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node2; // 形成环
        System.out.println("有环链表检测结果: " + solution.hasCycle(head2));
    }
}